//
//  MCTool.swift
//  StoreManage
//
//  Created by MC on 2018/8/31.
//  Copyright © 2018年 MC. All rights reserved.
//

import Foundation


//MARK: -系统相关 ========================================
public let MCSystem_APPVersion    = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
public let MCSystem_APPName       = Bundle.main.infoDictionary!["CFBundleDisplayName"] as! String
public let MCSystem_projectName   = Bundle.main.infoDictionary!["CFBundleName"] as! String

//-屏幕宽高
public let MCScreenWidth : CGFloat    = UIScreen.main.bounds.size.width
public let MCScreenHeight : CGFloat   = UIScreen.main.bounds.size.height

//-状态栏高度
public let MCStatusBarHeight : CGFloat   = UIApplication.shared.statusBarFrame.size.height
//-导航栏高度
public func MCNavigationBarHeight(_ target:UIViewController) -> CGFloat {
    if target.navigationController != nil {
        return target.navigationController?.navigationBar.frame.size.height ?? 44
    } else {
        return 44
    }
}
//-底部安全区域
public let MCSafeAreaBottomHeight : CGFloat  = (MCScreenHeight  == 812 ? 34 : 0)



//字体
public func MCFont(_ font : CGFloat) -> UIFont {
    return UIFont.systemFont(ofSize: font)
}


public func MCGetClassName(_ obj:Any) -> String {
    let mirro = Mirror(reflecting: obj)
    let className = String(describing: mirro.subjectType).components(separatedBy: ".").first!
    return className
}

//MARK: -获取缓存
public func MCFileSizeOfCache()-> String {
    let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
    let fileArr = FileManager.default.subpaths(atPath: cachePath!)
    var size = 0
    for file in fileArr! {
        let path = cachePath! + "/\(file)"
        // 取出文件属性
        let floder = try! FileManager.default.attributesOfItem(atPath: path)
        // 用元组取出文件大小属性
        for (abc, bcd) in floder {
            // 累加文件大小
            if abc == FileAttributeKey.size {
                size += (bcd as AnyObject).integerValue
            }
        }
    }
    let mm = size / 1024 / 1024
    return String(mm) + "M"
}

//Mark: -清理缓存
public func MCClearCache() {
    let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
    let fileArr = FileManager.default.subpaths(atPath: cachePath!)
    // 遍历删除
    for file in fileArr! {
        let path = cachePath! + "/\(file)"
        if FileManager.default.fileExists(atPath: path) {
            do {
                try FileManager.default.removeItem(atPath: path)
            } catch { }
        }
    }
}

//Mark: -适配机型  以6为基准
public func MCAdaptationModel(_ distance : CGFloat) -> CGFloat {
    if (MCScreenWidth == 320 && MCScreenHeight == 568) {  // 5的机型
        return distance * 0.85333333
    } else if (MCScreenWidth == 375 && MCScreenHeight == 667) { // 6 7 的机型
        return distance
    }  else if (MCScreenWidth == 414 && MCScreenHeight == 736) { // plus的机型
        return distance * 1.104
    }  else if (MCScreenWidth == 375 && MCScreenHeight == 812) { // X 的机型
        return distance
    } else {
        return distance
    }
}




//MARK: -通知 ========================================
public func MCNotification_addObserver(name:String,vc:Any,selector : Selector) -> Void {
    let notificationName = Notification.Name(rawValue: name)
    NotificationCenter.default.addObserver(vc, selector: selector, name: notificationName, object: nil)
}

public func MCNotification_post(name:String,object:Any?) -> Void {
    let notificationName = Notification.Name(rawValue: name)
    NotificationCenter.default.post(name: notificationName, object:object)
}

public func MCNotification_remove(vc:Any,name:String?) -> Void {
    NotificationCenter.default.removeObserver(vc, name: NSNotification.Name(rawValue: name!), object: nil)
}





//MARK: -UI 相关 =========================================
public func MCFindNavigationBarLine(view : UIView?) -> UIImageView? {
    
    if view == nil { return nil }
    if view!.isKind(of: UIImageView.classForCoder()) && view!.bounds.size.height <= 1 {
        return view as? UIImageView
    }
    for subView in view!.subviews {
        let imageView : UIImageView? = MCFindNavigationBarLine(view: subView)
        if imageView != nil {
            return imageView!
        }
    }
    return nil
}



//MARK: - 添加左右元素项
public func MCSetBarButtonItem_image(_ image: UIImage,target : UIViewController, selector : Selector,isLeft : Bool = false) -> UIBarButtonItem {
    
    var size = image.size
    
    if size.width < 40 { size.width = 40 }
    
    if size.height < 40 { size.height = 40 }
    
    
    let imageView = UIImageView()
    imageView.frame = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
    imageView.isUserInteractionEnabled = true
    imageView.image = image
    let tap = UITapGestureRecognizer.init(target: target, action: selector)
    imageView.addGestureRecognizer(tap)
    
    
    if isLeft {
        imageView.contentMode = UIViewContentMode.left
    } else {
        imageView.contentMode = UIViewContentMode.right
    }
    return UIBarButtonItem.init(customView: imageView)
}

public func MCSetBarButtonItem_text(_ text : String,textColor : UIColor = UIColor.MCWords,font : CGFloat = 14,target : UIViewController, selector : Selector,isLeft : Bool = false) -> UIBarButtonItem {
    
    var strWidth = text.MCString_getWidth(font: font, height: font + 4)
    
    
    if strWidth < 40 {
        strWidth = 40
    }
    
    
    let button = UIButton.init(type: UIButtonType.custom)
    button.frame = CGRect.init(x: 0, y: 0, width: strWidth, height: 40)
    button.addTarget(target, action: selector, for: UIControlEvents.touchUpInside)
    button.adjustsImageWhenHighlighted = false
    
    button.titleLabel?.font = UIFont.systemFont(ofSize: font)
    button.setTitle(text, for: UIControlState.normal)
    button.setTitleColor(textColor, for: UIControlState.normal)
    
    if isLeft {
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
    } else {
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right
    }
    
     return UIBarButtonItem.init(customView: button)
}



public func MCPushToViewController(current : UIViewController,target : UIViewController,isHiddenBottomBarWhenBack: Bool = true) {
    weak var weakSelf = current
    weakSelf?.hidesBottomBarWhenPushed = true
    weakSelf?.navigationController?.pushViewController(target, animated: true)
    weakSelf?.hidesBottomBarWhenPushed = isHiddenBottomBarWhenBack
}



// MARK: - MBProgressHUD
public func MCHUD_default(message: String?,view: UIView?, delay: CGFloat) {
    var text = message
    if text == nil { text = "加载中"}
    if view == nil { return }
    let hud = MBProgressHUD.showAdded(to: view!, animated: true)
    hud.label.text = text
    if delay != 0 { hud.hide(animated: true, afterDelay: TimeInterval(delay)) }
}
func MCHUD_text(message: String,view: UIView?,delay: Double) {
    if view == nil { return }
    let hud = MBProgressHUD.showAdded(to: view!, animated: true)
    hud.label.text = message
    hud.mode = MBProgressHUDMode.text
    hud.hide(animated: true, afterDelay: delay)
}
func MCHUD_custom(message: String,view: UIView?,delay: Double,image: String) {
    if view == nil { return }
    let hud = MBProgressHUD.showAdded(to: view!, animated: true)
    hud.label.text = message
    hud.mode = MBProgressHUDMode.customView
    hud.customView = UIImageView.init(image: UIImage.init(named: image))
    
    hud.hide(animated: true, afterDelay: delay)
}
public func MCHUD_hidden(view : UIView?) {
    if view == nil { return }
    MBProgressHUD.hide(for: view!, animated: true)
}






// MARK: - 微信分享
// 分享图片
public func MCWXShare_image(image:UIImage,compressionQuality:CGFloat,scane:WXScene) {
    
    let message = WXMediaMessage.init()
    let imageObject = WXImageObject.init()
    imageObject.imageData = UIImageJPEGRepresentation(image, compressionQuality)
    message.mediaObject = imageObject
    
    let req = SendMessageToWXReq.init()
    req.bText = false
    req.message = message
    req.scene = Int32(scane.rawValue)
    WXApi.send(req)
}
